package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登陆验证过滤器
 *
 * @author liqp
 * @version 1.0
 * @date 2022/9/14
 */
@WebFilter(urlPatterns = "/*", filterName = "loginCheckFilter")
@Slf4j
public class LoginCheckFilter implements Filter {
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1、获取本次请求的URI
        String currentUri = request.getRequestURI();
        log.info("过滤器中拦截到请求，uri:{}", currentUri); //   /employee/login

        //2、判断本次请求是否需要处理 ,哪些请求不需要处理？登陆，登出，静态资源
        //定义不需要请求的uri /employee/backend
        String[] uris = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/upload",
                "/common/download",
                "/user/sendMsg",
                "/user/login"
        };
        //匹配uri
        boolean flag = checkUri(currentUri, uris);
        if(flag) {
            //3、如果不需要处理，则直接放行
            log.info("当前请求无需处理 uri:{}", currentUri);
            filterChain.doFilter(request, response);
            return;
        }
        //4、判断员工登录状态，如果已登录，则直接放行
        Long employeeId = (Long) request.getSession().getAttribute("employee");
        if(employeeId != null) {
            long id = Thread.currentThread().getId();
            log.info("用户一登陆，放行 threadId:{}, uri:{} ", id, currentUri);
            //把当前登陆用户设置到本地线程中
            BaseContext.setCurrentId(employeeId);
            filterChain.doFilter(request, response);
            return;
        }

        //判断移动端用户登陆状态，如果已登陆，直接放行
        Long userId = (Long) request.getSession().getAttribute("user");
        if(userId != null) {
            log.info("用户一登陆，放行  uri:{} ", currentUri);
            //把当前登陆用户设置到本地线程中
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }

        //5、如果未登录则返回未登录结果(跳转到登陆页面)
        log.warn("用户未登陆，请先登陆 uri:{}" , currentUri);
        //{“code”:0, "msg":"NOTLOGIN"}
        R<Object> notLogin = R.error("NOTLOGIN");
        response.getWriter().write(JSON.toJSONString(notLogin));
    }

    private boolean checkUri(String currentUri, String[] uris) {
        for (String uri : uris) {
            if(ANT_PATH_MATCHER.match(uri, currentUri)) {
                //放行
                return true;
            }
        }
        return false;
    }
}